package com.sghd.football.module.game.service.core.task;

import com.sghd.common.socket.session.Session;
import com.sghd.common.socket.session.SessionManager;
import com.sghd.football.module.game.service.GameService;
import com.sghd.football.module.game.service.core.Desk;
import com.sghd.football.module.game.service.core.Player;
import com.sghd.football.module.game.service.model.Window;
import com.sghd.football.module.game.service.thread.Task;
import com.sghd.football.module.game.service.thread.TaskItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.Objects;

/**
 * @author wch
 * @date 2018-06-05 16:25
 * @desc 玩家长时间不操作，超时任务(返回大厅)，由匹配线程执行
 **/
public class TimeoutTask implements Task {
    private Logger logger = LoggerFactory.getLogger(getClass());
    private Player player;
    private int timeout;
    private GameService gameService;
    private SessionManager sessionManager;
    public TimeoutTask(Player player, int timeout, GameService gameService, SessionManager sessionManager) {
        this.player = player;
        this.timeout = timeout;
        this.gameService = gameService;
        this.sessionManager = sessionManager;
    }
    @Override
    public void run(Desk desk, Date now) {
        Date last = player.getLastUpdate();
        if ((now.getTime() - last.getTime()) >= timeout) {
            //超时强制清理玩家数据
            logger.debug("玩家[{}]超过3分名未操作，强制反回大厅！", player.getPlayerId());
            gameService.exit(player.getPlayerId(), false);
            gameService.dialog(Window.OP_TIMEOUT, player.getPlayerId());
            sessionManager.kick(Session.TIMEOUT, player.getPlayerId());
            player.setTmt(false);
        } else {
            //下一次超时检测(循环任务)
            gameService.addTimer(desk, this::run, new Date(last.getTime() + timeout), TaskItem.MATCH);
        }
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        TimeoutTask that = (TimeoutTask) o;
        return Objects.equals(player, that.player);
    }

    @Override
    public int hashCode() {
        return Objects.hash(player);
    }
}
